package com.centerm.structure.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.centerm.common.exception.MyRuntimeException;
import com.centerm.common.view.page.PageQueryResult;
import com.centerm.structure.dao.PermissionDao;
import com.centerm.structure.dao.RolePermissionDao;
import com.centerm.structure.domain.Permission;
import com.centerm.structure.dto.PermissionInfo;
import com.centerm.structure.dto.PermissionTreeInfo;
import com.centerm.structure.dto.RolePermissionInfo;
import com.centerm.structure.service.PermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 
* @ClassName: PermissionServiceImpl
* @Description: 权限服务实现类
* @author czy
* @date 2017年8月14日
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;

	@Override
	public PageQueryResult<PermissionInfo> pagePermissionInfoList(Integer pageNum,
			Integer pageSize,PermissionInfo permissionInfo) {
		Page<PermissionInfo> page = PageHelper.startPage(pageNum, pageSize);
        List<Permission> list = permissionDao.listByParam(permissionInfo);
        PageQueryResult<PermissionInfo> resultInfo = new PageQueryResult<PermissionInfo>(page, convertArrayResponse(list));
        return resultInfo;
	}
	

	@Override
	public List<PermissionTreeInfo> loadPermissionTree(Integer parentId) {
		PermissionTreeInfo permissionTreeInfo = null;
		List<PermissionTreeInfo> treeInfoList = new ArrayList<PermissionTreeInfo>();
		try {
			//组装权限节点
			List<Permission> permissionList = listPermissionByParentId(parentId);
			for (Permission permission : permissionList) {
				permissionTreeInfo = new PermissionTreeInfo(permission);
				List<PermissionTreeInfo> subTreeInfo = loadPermissionTree(permission
						.getId());
				permissionTreeInfo.setChildren(subTreeInfo);
				treeInfoList.add(permissionTreeInfo);
			}
		} catch (Exception e) {
			String errorMsg = "获取树结构错误!";
			throw new MyRuntimeException(errorMsg);
		}
		return treeInfoList;
	}

	@Override
	public List<PermissionTreeInfo> loadCurrentPermissionTree(Integer parentId) {
		PermissionTreeInfo permissionTreeInfo = null;
		List<PermissionTreeInfo> treeInfoList = new ArrayList<PermissionTreeInfo>();
		try {
			//组装权限节点
			List<Permission> permissionList = listPermissionByParentId(parentId);
			for (Permission permission : permissionList) {
				permissionTreeInfo = new PermissionTreeInfo(permission);
				treeInfoList.add(permissionTreeInfo);
			}
		} catch (Exception e) {
			String errorMsg = "获取树结构错误!";
			throw new MyRuntimeException(errorMsg);
		}
		return treeInfoList;
	}

	@Override
	public List<Permission> listPermissionByParentId(Integer parentId) {
		PermissionInfo permissionInfo = new PermissionInfo();
		permissionInfo.setParentId(parentId);
		//只获取有效的记录
		permissionInfo.setValid(1);
		// 根据父节点获取所有子权限
		List<Permission> permissionList = permissionDao
				.listByParam(permissionInfo);
		return permissionList;
	}
	
	@Override
	public Boolean existCode(String code) {
		if(StringUtils.isBlank(code)){
			throw new MyRuntimeException("权限code不能为空！");
		}
		PermissionInfo permissionInfo = new PermissionInfo();
		permissionInfo.setCode(code);
		List<Permission> list = permissionDao.listByParam(permissionInfo);
		return list.size()>0?true:false;
	}
	
	@Override
	public Integer insert(PermissionInfo permissionInfo) {
		Permission permission = convertRequest(permissionInfo);
		if(existCode(permission.getCode())){
			String errorMsg = "新增失败，权限编码已存在!";
			throw new MyRuntimeException(errorMsg);
		}
		//新增记录必定有效
		permission.setValid(1);
		Integer result = permissionDao.insert(permission);
		if(result!=1){
			String errorMsg = "新增权限错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		return permission.getId();
	}

	@Override
	public Integer update(PermissionInfo permissionInfo) {
		Permission permission = convertRequest(permissionInfo);
		if(StringUtils.isNotBlank(permission.getCode())){
			String errorMsg = "更新权限错误，权限编码不允许修改!";
			throw new MyRuntimeException(errorMsg);
		}
		Integer result =  permissionDao.update(permission);
		if(result!=1){
			String errorMsg = "更新权限错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		return result;
	}
	
	@Override
	@Transactional
	public Integer delete(Integer id) {
		//先判断是否有角色使用该权限
		RolePermissionInfo rolePermisson = new RolePermissionInfo();
		rolePermisson.setPermissionId(id);
		List<RolePermissionInfo> rolePermissionList = rolePermissionDao.listByParam(rolePermisson);
		if(rolePermissionList!=null&&rolePermissionList.size()>0){
			String errorMsg = "有角色使用该权限，故无法删除!";
			throw new MyRuntimeException(errorMsg);
		}
		//正式删除权限
		Integer result =  permissionDao.deleteById(id);
		if(result!=1){
			String errorMsg = "删除权限错误，请排查!";
			throw new MyRuntimeException(errorMsg);
		}
		return result;
	}
	
	@Override
	public List<Permission> listByParam(PermissionInfo permissionInfo) {
		List<Permission> list = permissionDao.listByParam(permissionInfo);
		return list;
	}

	@Override
	public Boolean isChild(Integer parentId, Integer childId) {
		Boolean b = false;
		//1.parentId为0是顶层根节点，所以必包含；2.相等时也是包含关系
		if(parentId==0||parentId.equals(childId)){
			b = true;
		} else {
			//如果childId为顶层节点，表示遍历完成也没匹配到，退出递归，返回false
			if(childId == 0){
				return false;
			}
			PermissionInfo permissionInfo = getById(childId);
			b = isChild(parentId,permissionInfo.getParentId());
		}
		return b;
	}
	
	@Override
	public PermissionInfo getById(Integer id) {
		Permission permission = permissionDao.getById(id);
		return convertResponse(permission);
	}
	
	@Override
	public List<Permission> listUserPermsssion(Integer userId) {
		return permissionDao.listUserPermsssion(userId);
	}
	
	@Override
	public List<String> listUserPermsssionCode(Integer userId) {
		return permissionDao.listUserPermsssionCode(userId);
	}
	
	private Permission convertRequest(PermissionInfo permissionInfo) {
		//TODO czy 该转换方法并不正式，存在风险
		return JSON.parseObject(JSON.toJSONString(permissionInfo), Permission.class);
	}
	
	private PermissionInfo convertResponse(Permission permission) {
		//TODO czy 该转换方法并不正式，存在风险
		return JSON.parseObject(JSON.toJSONString(permission), PermissionInfo.class);
	}
	
	private List<PermissionInfo> convertArrayResponse(List<Permission> permissionlist) {
		//TODO czy 该转换方法并不正式，存在风险
		return JSON.parseArray(JSON.toJSONString(permissionlist), PermissionInfo.class);
	}
}
